package com.at.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author : code1997
 * @date :2020-09-2020/9/24 15:49
 */
@Aspect
@Component
public class LogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /*定义切面：controller包下所有的所有类，所有方法，任意参数*/
    @Pointcut("execution(* com.at.controller.*.*(..))")
    public void log(){

    }
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        /*获取HttpServletRequest对象*/
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        /*获取切的方法的全类名*/
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        /*定义自定义类来进行日志数据的封装*/
        ReqeustLog reqeustLog = new ReqeustLog(
                request.getRequestURL().toString(),
                request.getRemoteAddr(),
                classMethod,
                joinPoint.getArgs()
        );
        logger.info("Rquest  ----- {}",reqeustLog);
    }

    @After("log()")
    public void doAfter() {

    }

    /*使用result来接收returning的值*/
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAtfertRturning(Object result) {
        logger.info("Return ------ {}",result );
    }

    /*定义一个内部类来实现日志记录*/
    private class ReqeustLog {
            private String url;
            private String ip;
            private String classMethod;
            private Object[] args;

            public ReqeustLog(String url, String ip, String classMethod, Object[] args) {
                this.url = url;
                this.ip = ip;
                this.classMethod = classMethod;
                this.args = args;
            }

            @Override
            public String toString() {
                return "ReqeustLog{" +
                        "url='" + url + '\'' +
                        ", ip='" + ip + '\'' +
                        ", classMethod='" + classMethod + '\'' +
                        ", args=" + Arrays.toString(args) +
                        '}';
            }
        }


}

